package com.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.dom4j.Attribute;
import org.dom4j.CDATA;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.MainFrame;
import com.model.ImgModel;
import com.model.XMLImgModel;
import com.ui.impl.XMLAndFileModifyPanel;

public class FileUtils {
	/**
	 * 备份一个文件
	 * @param filePath
	 * @return
	 */
	public static String backUpAFileByAbsPath(String filePath){
		File dir = new File(Constants.BACKUPDIR);
		if(!dir.exists()){
			dir.mkdirs();
		}
		File srcFile = new File(filePath);
		File dstFile = new File(dir.getPath()+"/"+srcFile.getName());
		try {
			if(dstFile.exists() && dstFile.length()==srcFile.length()){
				return dstFile.getAbsolutePath();
			}else{
				dstFile = new File(dir.getPath()+"/"+System.currentTimeMillis()+srcFile.getName());
			}
			
			dstFile.createNewFile();
			
			fileChannelCopy(srcFile,dstFile);
	
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return dstFile.getAbsolutePath();
	}
	
	/**
	 * 拷贝一个文件到另外一个文件
	 * @param s
	 * @param t
	 * @throws IOException
	 */
	public static void fileChannelCopy(File s, File t) throws IOException {

		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;

		try {
			fi = new FileInputStream(s);
			fo = new FileOutputStream(t);
			in = fi.getChannel();// 得到对应的文件通道
			out = fo.getChannel();// 得到对应的文件通道
			in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(fi!=null){
				fi.close();
			}
			if(in!=null){
				in.close();
			}
			if(fo!=null){
				fo.close();
			}
			if(out!=null){
				out.close();
			}
		}
	}
	
	/**
	 * 替换一个文件
	 * @param newFilePath
	 * @param oldFilePath
	 * @return
	 * @throws IOException 
	 */
	public static void replaceAFile(String newFilePath,String oldFilePath) throws IOException{
			File fileOld = new File(oldFilePath);
//			backUpAFile(oldFilePath);
			File fileNew = new File(newFilePath);
			
			fileChannelCopy(fileNew,fileOld);
			
	}
	
	/**
	 * 删除一个文件夹
	 * @param dirpath
	 * @return
	 */
	public static boolean deleteADir(String dirpath){
		File dirFile = new File(dirpath);  
		if (!dirFile.exists() || !dirFile.isDirectory()) {  
	        return false;  
	    }
		boolean flag = true;
		File[] files = dirFile.listFiles(); 
		for (int i = 0; i < files.length; i++) {  
	        //删除子文件  
	        if (files[i].isFile()) {  
	            flag = files[i].delete();  
	            if (!flag) break;  
	        } //删除子目录  
	        else {  
	            flag = deleteADir(files[i].getAbsolutePath());  
	            if (!flag) break;  
	        }  
	    }  
	    if (!flag) return false;  
	    //删除当前目录  
	    if (dirFile.delete()) {  
	        return true;  
	    } else {  
	        return false;  
	    } 
	}
	
	public static void openFileByNotePad(String filePath){
		
		Runtime runtime = Runtime.getRuntime();
		String cmdStr = "notepad "+filePath ;
		try {
			Process exec = runtime.exec(cmdStr);
//			exec.destroy();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static List<XMLImgModel> loadImgConfig2() throws Exception{
		List<XMLImgModel>  retList = new ArrayList<XMLImgModel>();
		

		SAXReader reader = new SAXReader();
		Document  document = reader.read(loadAFile("/com/res/ImgConf.xml"));  
		Element root = document.getRootElement();  

		List childs = root.elements();
		Iterator iter = childs.iterator();
		while(iter.hasNext()){
			Element next = (Element) iter.next();
			Attribute nameAtt = next.attribute("name");
			XMLImgModel xmlIm = new XMLImgModel();
			xmlIm.setName(nameAtt.getValue());
			
			List elements = next.elements();
			int size = elements.size();
			for(int i=0;i<size;i++){
				ImgModel im = new ImgModel();
				Element next2 = (Element)elements.get(i);
				String tmpPath = next2.node(0).getText().trim();
				Attribute wa = next2.attribute("width");
				Attribute ha = next2.attribute("height");

				im.setRPath(tmpPath);
				im.setWidth(Integer.parseInt(wa.getValue().trim()));
				im.setHeight(Integer.parseInt(ha.getValue().trim()));
				im.setFormat(tmpPath.substring(tmpPath.indexOf(".")+1));
				im.setName(tmpPath.substring(tmpPath.lastIndexOf("/")+1));
				
				xmlIm.addImgModel(im);
			}
			ImgModel imgModel = xmlIm.getImgsList().get(0);
			
			xmlIm.setDefaultFormat(imgModel.getFormat());
			xmlIm.setDefaultPath(imgModel.getRPath());
			xmlIm.setDefaultW(imgModel.getWidth());
			xmlIm.setDefaultH(imgModel.getHeight());
			retList.add(xmlIm);
		}
		
		return retList;
	}
	
	public static File loadAFile(String filePath) throws URISyntaxException{
		File retFile = new File(FileUtils.class.getResource(filePath).toURI());
		return retFile;
	}
	
	
	public static void setXMLNodeAttr(String nodeName,String attrName,String attrValue,String xmlPath) throws Exception{
		SAXReader reader = new SAXReader();
		Document  document = reader.read(new File(xmlPath));  
		Element root = document.getRootElement();  
		
		Element findElement = findElementByName(root,nodeName);
		findElement.attribute(attrName).setValue(attrValue);
		saveXML(document, xmlPath);
	}
	
	public static String getXMLNodeAttr(String nodeName,String attrName,String xmlPath) throws Exception{
		SAXReader reader = new SAXReader();
		Document  document = reader.read(new File(xmlPath));  
		Element root = document.getRootElement();  
		
		Element findElement = findElementByName(root,nodeName);
		return findElement.attributeValue(attrName);
	}
	
	public static void setXMLNodeValue(String nodeName,String nodeValue,String xmlPath) throws Exception{
		SAXReader reader = new SAXReader();
		Document  document = reader.read(new File(xmlPath));  
		Element root = document.getRootElement();  
		
		Element findElement = findElementByName(root,nodeName);
		findElement.node(0).setText(nodeValue);
		saveXML(document,xmlPath);
	}
	
	public static void setMultiXMLNodeValue(String nodeName[],String nodeValue[],String xmlPath) throws Exception{
		SAXReader reader = new SAXReader();
		Document  document = reader.read(new File(xmlPath));  
		Element root = document.getRootElement();  
		for(int i=0;i<nodeName.length;i++){
			Element findElement = findElementByName(root,nodeName[i]);
			findElement.node(0).setText(nodeValue[i]);
		}
		saveXML(document,xmlPath);
	}
	
	public static void setXMLNodeValueByMultiValues(String nodeName,String nodeValue[],String xmlPath) throws Exception{
		SAXReader reader = new SAXReader();
		Document  document = reader.read(new File(xmlPath));  
		Element root = document.getRootElement();  
		Element findElement = findElementByName(root,nodeName);
		if(findElement!=null && findElement.nodeCount() ==1){
			findElement.node(0).setText(nodeValue[0]+nodeValue[1]);
			return;
		}
		for(int i=0;i<nodeValue.length;i++){
			findElement.node(i).setText(nodeValue[i]);
		}
		
		saveXML(document,xmlPath);
	}
	
	public static String getXMLNodeValue (String nodeName,String xmlPath) throws Exception{
		SAXReader reader = new SAXReader();
		Document  document = reader.read(new File(xmlPath));  
		Element root = document.getRootElement();  
		
		Element element = findElementByName(root,nodeName);
		
		return element.node(0).getText().trim();
	}
	
	/**
	 * 找到 名字相同的第一个元素
	 * @param root
	 * @param eleName
	 * @return
	 */
	public static Element findElementByName(Element root,String eleName){
		Element retEle = null;
		
		if(root.getName().equals(eleName)){
			return root;
		}
//		System.out.println(root.getName());
		Iterator iter = root.elements().iterator();
		while(iter.hasNext()){
			Element next = (Element)iter.next();
			if(next.getName().equals(eleName)){
				return next;
			} else {
				Element findElementByName = findElementByName(next,eleName);
				if(findElementByName!=null){
					return findElementByName;
				}
			}
		}
		
		return retEle;
	}
	
	public static void saveXML(Document  doc,String xmlPath) throws Exception{
		   OutputFormat format = OutputFormat.createPrettyPrint();  
	        // 利用格式化类对编码进行设置  
	        format.setEncoding("UTF-8");  
	        FileOutputStream output = new FileOutputStream(new File(xmlPath));  
	        XMLWriter writer = new XMLWriter(output, format);  
	        writer.write(doc);  
	        writer.flush();  
	        
	        writer.close();
	        output.close();
	}
	
	public static Properties loadPropertiesByAbsPath(String proFilePath) throws FileNotFoundException, IOException{
		Properties ret = null;
		
		ret = new Properties();
		FileInputStream fileInputStream = new FileInputStream(new File(proFilePath));
		ret.load(fileInputStream);
		fileInputStream.close();
		
		return ret;
	}
	
	public static void saveProFile(Properties pro, String absPath) throws IOException{
//		String tmpPath = "D:/newPro.properties";
		File file = new File(absPath);
		if(!file.exists()){
			file.createNewFile();
		}
		FileOutputStream fos = new FileOutputStream(file);
		pro.store(fos, null);//new Date().toString()
		fos.close();
	}
	
	public static void replaceAllAssignValue(String path,String[] keyWords,String[] replaceStrs) throws FileNotFoundException, IOException{
		Properties pros = loadPropertiesByAbsPath(path);
		
		Set<Entry<Object,Object>> entrySet = pros.entrySet();
		Iterator<Entry<Object, Object>> iter = entrySet.iterator();
		while(iter.hasNext()){
			Entry<Object, Object> next = iter.next();
			String proKey = next.getKey().toString();
			String proValue = next.getValue().toString();
			
			for(int i=0;i<keyWords.length;i++){
				if(proValue.contains(keyWords[i])){
					String replaceAll = proValue.replaceAll(keyWords[i], replaceStrs[i]);
					pros.setProperty(proKey, replaceAll);
				}
			}
		}
		
		saveProFile(pros,path);
	}
	
	public static void chageAllAssignValue(String path,String keys[],String values[]) throws FileNotFoundException, IOException{
		Properties pros = loadPropertiesByAbsPath(path);
		for(int i=0;i<keys.length;i++){
			pros.setProperty(keys[i],values[i]);
		}
		saveProFile(pros,path);
	}
	
	public static void replaceAllAssignValue(String path,String[] keyWords,String[] replaceStrs,String keys[],String values[]) throws FileNotFoundException, IOException{
		Properties pros = loadPropertiesByAbsPath(path);
		
		for(int i=0;i<keys.length;i++){
			pros.setProperty(keys[i],values[i]);
		}
		
		Set<Entry<Object,Object>> entrySet = pros.entrySet();
		Iterator<Entry<Object, Object>> iter = entrySet.iterator();
		while(iter.hasNext()){
			Entry<Object, Object> next = iter.next();
			String proKey = next.getKey().toString();
			String proValue = next.getValue().toString();
			
			for(int i=0;i<keyWords.length;i++){
				if(proValue.contains(keyWords[i])){
					String replaceAll = proValue.replaceAll(keyWords[i], replaceStrs[i]);
					pros.setProperty(proKey, replaceAll);
				}
			}
		}
		
		saveProFile(pros,path);
	}
	
	public static String changeToUnicode(String strInput){
		if(strInput == null || strInput ==""){
			return "";
		}
		int length = strInput.length();
		StringBuffer sb = new StringBuffer();
		for(int i = 0;i<length;i++){
			char cTemp = strInput.charAt(i);
			int min = Integer.valueOf("4e00",16);
			int max = Integer.valueOf("9fa5",16);
			int now = Integer.valueOf(cTemp);
			if(min<=now && now <= max){
				String hexStr = Integer.toHexString(cTemp);
				String newStr = "";
				int hexLen = hexStr.length();
				for(int j = 0;j<(4-hexLen);j++){
					newStr = newStr+"0";
				}
				sb.append("\\u"+newStr+hexStr);
			}else{
				sb.append(cTemp);
			}
		}
		return sb.toString();
	}
	
	///////////////////测试
	public static void main(String[] args) throws Exception {
		
//		String proPath = "D:/newBDEpon/BroadDirector5/install/html/EnglishToNative_zh_CN.properties";
//		String dstPath = "D:/EnglishToNative_zh_CN.properties";
//		Properties loadPropertiesByAbsPath = loadPropertiesByAbsPath(proPath);
//		String title1 = loadPropertiesByAbsPath.getProperty("AdventNet");
//		String title2 = loadPropertiesByAbsPath.getProperty("WebNMS");
//		String title3 = loadPropertiesByAbsPath.getProperty("<PROMINENT_KEY>Application");
//		String title4 = loadPropertiesByAbsPath.getProperty("<PROMINENT_KEY>Version x.x");
//		System.out.println(title1+","+title2+","+title3+","+title4);
//		
//		System.out.println(loadPropertiesByAbsPath.getProperty("AdventNet\t\t\t"));
		
//		Properties pros = loadPropertiesByAbsPath(proPath);
//		System.out.println(pros.size());
		
//		Properties pro = new Properties();
//		pro.load(new FileInputStream(new File("statistics/aaaa.properties")));
//		pro.put("key1", "ccc");
//		System.out.println(pro.getProperty("key1"));
		
		// System.out.println(getXMLNodeValue(XMLAndFileModifyPanel.versionNodeTag,MainFrame.projectPath+XMLAndFileModifyPanel.setupPath));
		// setXMLNodeValue(XMLAndFileModifyPanel.versionNodeTag,"bbb",MainFrame.projectPath+XMLAndFileModifyPanel.setupPath);
		// System.out.println(getXMLNodeValue(XMLAndFileModifyPanel.versionNodeTag,MainFrame.projectPath+XMLAndFileModifyPanel.setupPath));

//		System.out.println(getXMLNodeAttr(XMLAndFileModifyPanel.urlNodeTag,
//				XMLAndFileModifyPanel.urlTag, MainFrame.projectPath
//						+ XMLAndFileModifyPanel.clientParamPath));
//		
//		setXMLNodeAttr(XMLAndFileModifyPanel.urlNodeTag,
//				XMLAndFileModifyPanel.urlTag, "www.baidu.com/",
//				MainFrame.projectPath + XMLAndFileModifyPanel.clientParamPath);
//		
//		System.out.println(getXMLNodeAttr(XMLAndFileModifyPanel.urlNodeTag,
//				XMLAndFileModifyPanel.urlTag, MainFrame.projectPath
//						+ XMLAndFileModifyPanel.clientParamPath));

		// System.out.println(Constants.USERDIR);
		// backUpAFile("C:/Documents and Settings/Administrator/桌面/OSWorkFlow.doc");
		//
		// replaceAFile("C:/Documents and Settings/Administrator/桌面/success.png",
		// "D:/JEEWorkSpace/OMETool/failed.png");

		// System.out.println(deleteADir("D:/JEEWorkSpace/OMETool/_tmpDir_"));
		
//		String path = "D:/git/SwingDemo/OMETool/_tmpDir_/zip/AdventNetAboutDialog/AboutDialogProps.xml";
//		System.out.println(getXMLNodeValue("CopyrightInfo", path));
//		setXMLNodeValue("CopyrightInfo", "aaa", path);
//		System.out.println(getXMLNodeValue("CopyrightInfo", path));
		
		String path = "C:/Documents and Settings/Administrator/桌面/OEMTOOL/a/AboutDialogProps.xml";
//		String nodeName = "CopyrightInfo";
////		String xmlNodeValue = getXMLNodeValue(nodeName, path);
////		System.out.println(xmlNodeValue);
//		char a = 169;
//		setXMLNodeValueByMultiValues(nodeName, new String[]{a+"","aaaaaaaa"}, path);
		
//		System.out.println(a+"");
//		System.out.println(changeToUnicode("轻微"));
		
		
		char a = 169;
		SAXReader reader = new SAXReader();
		Document  document = reader.read(new File(path));  
		Element root = document.getRootElement();  
		Element findElement = findElementByName(root,"CopyrightInfo");
		System.out.println(findElement.nodeCount());
		System.out.println(findElement.node(1).getText());
		String path2 = "C:/Documents and Settings/Administrator/桌面/OEMTOOL/a";
		String fileName = "/AdventNetAboutDialog.jar";
//		ZipUtils.releaseAJarFile(path2+fileName, path2, 512);
	}
}
